package com.ibeetl.admin.core.web.util;

import com.ibeetl.admin.core.util.VerifyCodeUtils;
import com.ibeetl.admin.core.web.JsonResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.ext.simulate.WebSimulate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 没有找到匹配的Controller
 * 
 * @author xiandafu
 *
 */
@Controller
public class VerifyCodeController {
	@Autowired
	WebSimulate webSimulate;
	Log log = LogFactory.getLog(VerifyCodeController.class);
	private static final String MODEL = "/core";
	@RequestMapping(value = MODEL + "/verify/image", method = RequestMethod.GET)
	public void authImage(String token, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 生成随机字串
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		session.removeAttribute(token + "-verCode");
		session.removeAttribute(token + "-codeTime");

		session.setAttribute(token + "-verCode", verifyCode.toLowerCase());
		session.setAttribute(token + "-codeTime", LocalDateTime.now());

		// 生成图片
		int w = 100, h = 30;
		OutputStream out = response.getOutputStream();
		VerifyCodeUtils.outputImage(w, h, out, verifyCode);
	}

	/**
	 * 校验验证码
	 * 
	 * @param code
	 * @param request
	 */
	@RequestMapping(MODEL + "/validVeirfyCode")
	@ResponseBody
	public JsonResult validVeirfyCode(String code, String token, HttpServletRequest request, HttpSession session) {
		String verCode = (String)session.getAttribute(token + "-verCode");
		if (null == verCode) {
			return JsonResult.failMessage("验证码已失效");
		}
		String verCodeStr = verCode.toString();
		LocalDateTime localDateTime = (LocalDateTime) session.getAttribute(token + "-codeTime");

		long past = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
		long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

		if (verCodeStr == null || code == null || code.isEmpty() || !verCodeStr.equalsIgnoreCase(code)) {
			return JsonResult.failMessage("验证码错误");
		} else if ((now - past) / 1000 / 60 > 10) {// 10分钟
			return JsonResult.failMessage("验证码已过期，重新获取");
		} else {
			return JsonResult.success();
		}
	}

}
